<link rel="stylesheet" href="${request.contextPath}/assets/bower_components/jquery-ztree/zTreeStyle.css">
<section class="content-header">
	<h1>&nbsp;</h1>
	<ol class="breadcrumb">
		<li><a><i class="fa fa-dashboard"></i>信息管理</a></li>
		<li class="active"><a>车辆管理</a></li>
	</ol>
</section>
<!-- Main content -->
<section class="content" id="deviceContent">
	<div class="row">
		<div class="col-xs-12">
			<div class="box">
				<div class="box-body">
					<!-- 搜索条件 -->
					<table class="table">
						<tr height="45px" bgcolor="#F3F3F3">
						    <td align="left" style="width:250px;">
								<form action="#" method="get" class="">
							        <div class="input-group">
							          <input type="text" name="q" class="form-control" placeholder="Search...">
							              <span class="input-group-btn">
							                <button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
							                </button>
							              </span>
							        </div>
							      </form>
							</td>
							<td align="left">
								<button	class="btn btn-danger btn-small" data-toggle="modal" onclick="showadddialog();">添加</button>								
							</td>
						</tr>
					</table>
					<!-- 结果列表 -->
					<table id="myTableData"
						class="table table-bordered table-condensed table-hover table-striped">
						<thead>
							<tr>
								<th>ID</th>
								<th>序号</th>
								<th>车牌号</th>
								<th>车牌颜色</th>
								<th>车辆颜色</th>
								<th>所属公司</th>
								<th>状态</th>
								<th>设备号</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
</section>

<div class="modal fade" id="modal-default">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">添加车辆</h4>
      </div>
      <div class="modal-body">
        
        <form class="form-horizontal" id="defaultForm">
              <div class="box-body">
              
                <div class="form-group">
                  <label class="col-sm-2 control-label">所属公司</label>
                  <div class="col-sm-9">
                    	<input class='link-url form-control' id='pid' type='text'
								onclick="showMenu();" placeholder='选择公司' readonly="true"/>
						<input type="hidden" id="parentid" />
						<div id="menuContent" class="menuContent"
							style="display:none;position: absolute;z-index:999">
							<ul id="treeDemo" class="ztree"
								style="margin-top:0; width:130%;min-height: 215px;"></ul>
						</div>
                  </div>
                </div>
                <div class="form-group">
                   <input type="hidden" class="form-control" id="vehinfoid">
                  <label for="vehid" class="col-sm-2 control-label">车牌号</label>
                  <div class="col-sm-9">
                    <input type="text" class="form-control" id="vehid" name="vehid" placeholder="车牌号:苏B117Q9">
                  </div>
                  <div class="col-sm-1">
                  	<span class="promptMsg" id="promptMsg_device_id4">*</span>
                  </div>
                </div>
                <div class="form-group">
                  <label for="platetype" class="col-sm-2 control-label">车牌颜色</label>
                  <div class="col-sm-9">
                    <select id="platetype" name="platetype" class="form-control">
                    	<option value="蓝牌">蓝牌</option>
                    	<option value="黄牌">黄牌</option>
                    	<option value="黑牌">黑牌</option>
                    	<option value="白牌">白牌</option>
                    	<option value="绿牌">绿牌</option>
                    	<option value="黄绿">黄绿</option>
                    	<option value="农黄">农黄</option>
                    	<option value="其他">其他</option>
                    </select>
                  </div>
                </div>
                <div class="form-group">
                  <label for="vehcolor" class="col-sm-2 control-label">车辆颜色</label>
                  <div class="col-sm-9">
                    <input type="text" class="form-control" id="vehcolor" placeholder="黑色">
                  </div>
                </div>
                <div class="form-group">
                  <label for="status" class="col-sm-2 control-label">状态</label>
                  <div class="col-sm-9">
                    <select id="status" name="status" class="form-control">
                    	<option value="0" selected="selected">正常</option>
                    	<option value="1">维修</option>
                    	<option value="2">停用</option>
                    	<option value="3">欠费</option>
                    </select>
                  </div>
                </div>
                <div class="form-group">
                  <label for="vehtype" class="col-sm-2 control-label">车辆类型</label>
                  <div class="col-sm-9">
                    <select id="vehtype" name="vehtype" class="form-control">
                    </select>
                  </div>
                  <div class="col-sm-1">
                  	<span class="promptMsg" id="promptMsg_device_id4">*</span>
                  </div>
                </div>
              </div>
              
              <div class="box-footer">
              	<div class="pull-right">
	              	<button type="button" id="saveveh" class="btn btn-info">确定</button>
	                &nbsp;&nbsp;&nbsp;&nbsp;<button type="button" class="btn btn-default pull-right" data-dismiss="modal">取消</button>
              	</div>
              </div>
              
            </form>
      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="modal-default2">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">快速加设备</h4>
      </div>
      <div class="modal-body">
      <input type="hidden" class="form-control" id="selveh">
            <table id="myTableData2"
				class="table table-bordered table-condensed table-hover table-striped">
				<thead>
					<tr>
						<th>设备号</th>
						<th>序列号</th>
						<th>设备类型</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody id="mydev">
				<tr>
					<td>111</td>
					<td>222</td>
					<td>333</td>
					<td>444</td>
					<td>555</td>
				</tr>
				</tbody>
			</table>
      </div>
      <!-- <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" onclick="saveveh();">保存</button>
      </div> -->
    </div>
  </div>
</div>
	<script type="text/javascript"
		src="${request.contextPath}/assets/bower_components/jquery-ztree/jquery.ztree.core-3.5.min.js"></script>
	<script type="text/javascript"
		src="${request.contextPath}/assets/bower_components/jquery-ztree/jquery.ztree.exedit-3.5.min.js"></script>
		
<script>
   
   $(function(){
	 $("#myTableData").dataTable({
		 lengthMenu: [10],//这里也可以设置分页，但是不能设置具体内容，只能是一维或二维数组的方式，所以推荐下面language里面的写法。
         paging: true,//分页
         ordering: true,//是否启用排序
         searching: false,//搜索
         language: {
       	  lengthMenu: '',//左上角的分页大小显示。
             paginate: {//分页的样式内容。
                 previous: "上一页",
                 next: "下一页",
                 first: "首页",
                 last: "末页"
             },
             zeroRecords: "没有内容",//table tbody内容为空时，tbody的内容。
             //下面三者构成了总体的左下角的内容。
             info: "总共_PAGES_ 页，显示第_START_ 到第 _END_条记录 ，记录总数： _TOTAL_条 ",//左下角的信息显示，大写的词为关键字。
             infoEmpty: "0条记录",//筛选为空时左下角的显示。
             infoFiltered: ""//筛选之后的左下角筛选提示，
         },
         pagingType: "full_numbers",//分页样式的类型
         "serverSide": true,
          ajax: function (data, callback, settings) {
              //封装请求参数
              var param = {};
              param.limit = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
              param.start = data.start;//开始的记录序号
              param.page = (data.start / data.length)+1;//当前页码
              param.orderby=data.orderBys;
              //ajax请求数据
              $.ajax({
                  type: "post",
                  url: "${request.contextPath}/vehicleinfo/getVehicleList",
                  cache: false,  //禁用缓存
                  data: param,  //传入组装的参数
                  dataType: "json",
                  success: function (result) {
                      //封装返回数据
                      var returnData = {};
                      returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                      returnData.recordsTotal = result.total;//返回数据全部记录
                      returnData.recordsFiltered = result.total;//后台不实现过滤功能，每次查询均视作全部结果
                      returnData.data = result.pageData;//返回的数据列表
                      //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                      //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                      callback(returnData);
                  }
              });
          },
          //列表表头字段
          columns: [
              { "data": "id" },
              { "data": null},
              { "data": "vehid" },
              { "data": "platetype" },
              { "data": "vehcolor" },
              { "data": "orgname" },
              { "data": "status" },
              { "data": "devicecode"},
              { "data": null}
          ],
         fnDrawCallback  : function(){
             this.api().column(1).nodes().each(function(cell, i) {
                 cell.innerHTML =  i + 1;
             });
         },
          "aoColumnDefs":[
              {
                  "targets":0,
                  "visible":false
              },
              {//倒数第一列
                  "targets":-1,
                  "bSortable": false,
                  render: function(data, type, row) {
                      var html ='<button class="btn btn-success btn-small" onclick="showeditdialog(\''+data.id+'\');">编辑</button>'
                      +'&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-success btn-small" onclick="showdevdialog(\''+data.id+'\');">快速加设备</button>'
                      +'&nbsp;&nbsp;&nbsp;&nbsp;<button class="btn btn-danger btn-small" onclick="delveh(\''+data.id+'\');">删除</button>';
                      return html;
                  }
              },
           ]
      });
	
	   $.ajax({
			url : "${request.contextPath}/user/getTreeOrg",
			type : "post",
			success : function(data) {
				if (data.success && data.other) {
				   var setting = {
				   		view: {
				   			dblClickExpand: true
				   		},
				   		data: {
				   			simpleData: {
				   				enable: true
				   			}
				   		},
				   		callback: {
				   			onClick: onClick
				   		}
				   	};
				   var treeData = formatTreeImage(data.other);
			       $.fn.zTree.init($("#treeDemo"), setting, treeData);
			       $.fn.zTree.getZTreeObj("treeDemo").expandAll(true);//展开
				}
			}
		});
	   
	   var data = {type:'vehicle_type'};
		 $.ajax({
				url : "${request.contextPath}/user/getDic",
				type : "post",
				data : data,
				success : function(s) {
					if (s.success) {
						var industrytypeArr = s.other;
						$("#vehtype").empty();
	        			for(var i=0;i<industrytypeArr.length;i++){
	        				$("#vehtype").append("<option value='"+industrytypeArr[i].key+"'>"+industrytypeArr[i].value+"</option>");
	        			}
					}
				}
			});
		 
		 $('#defaultForm').bootstrapValidator({
		        message: '此值无效',
		        feedbackIcons: {
		            valid: 'glyphicon glyphicon-ok',
		            invalid: 'glyphicon glyphicon-remove',
		            validating: 'glyphicon glyphicon-refresh'
		        },
		        fields: {
		        	vehid: {
		                validators: {
		                    notEmpty: {
		                        message: '车牌号不能为空'
		                    },
		                    regexp: {
		                        regexp: /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$/,
		                        message: '车牌号不符合规则'
		                      }
		                }
		            },
		            vehtype:{
		                validators: {
		                    notEmpty: {
		                        message: '车辆类型不能为空'
		                    }
		                }
		            }
		        }
		    });
		   
		   $("#saveveh").on("click", function(){
			     //获取表单对象
			    var bootstrapValidator = $('#defaultForm').data('bootstrapValidator');
		        //手动触发验证
		        bootstrapValidator.validate();
		        if(bootstrapValidator.isValid()){
		            //表单提交的方法、比如ajax提交
		            saveveh();
		        }
			});
   }); 
   
   	function onClick(e, treeId, treeNode) {
   		var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
   		nodes = zTree.getSelectedNodes(),
   		v = "";
   		pv = "";
   		nodes.sort(function compare(a,b){return a.id-b.id;});
   		for (var i=0, l=nodes.length; i<l; i++) {
   			v += nodes[i].name + ",";
   			pv += nodes[i].id + ",";
   		}
   		if (v.length > 0 ) v = v.substring(0, v.length-1);
   		var cityObj = $("#pid");
   		cityObj.attr("value", v);
   		
   		if (pv.length > 0 ) pv = pv.substring(0, pv.length-1);
   		var cityObj2 = $("#parentid");
   		cityObj2.attr("value", pv);
   		
   		hideMenu();
   	}

   	function showMenu() {
   		var cityObj = $("#pid");
   		var cityOffset = $("#pid").offset();
   		$("#menuContent").slideDown("fast");
   		$("body").bind("mousedown", onBodyDown);
   	}
   	function hideMenu() {
   		$("#menuContent").fadeOut("fast");
   		$("body").unbind("mousedown", onBodyDown);
   	}
   	function onBodyDown(event) {
   		if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
   			hideMenu();
   		}
   	}
   	
   function showadddialog()
   {
	   $("#vehinfoid").val(-1);
	   
	   $("#vehid").removeAttr("readonly");
	   $("#vehid").val("");
	   $("#platetype").val("");
	   $("#vehcolor").val("");
	   $("#status").val("0");
	   $("#vehtype").val("");
		
	   $("#modal-default").modal('show');
   }
   
   function showeditdialog(id)
   {
	   $("#vehinfoid").val(id);
	   
	   var data = {id:id}
	   $.ajax({
			url : "${request.contextPath}/vehicleinfo/getVehinfo",
			type : "post",
			data : data,
			success : function(s) {
				if (s.success) {
					
				    var veh = s.other;
				    
				    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
				    var snode = zTree.getNodeByParam("id",veh.companyid, null);
				    if (snode)
			    	{
				    	$("#pid").attr("value",snode.name);
					    zTree.selectNode(snode);
					    $("#parentid").attr("value", veh.companyid);
			    	}
				    else
			    	{
				    	$("#pid").attr("value",'选择公司');
				    	$("#parentid").attr("value", 0);
			    	}
				    
				    $("#vehid").attr("readonly","readonly");
				    
				    $("#vehid").val(veh.vehid);
				    $("#platetype").val(veh.platetype);
				    $("#vehcolor").val(veh.vehcolor);
				    $("#status").val(veh.status);
				    $("#vehtype").val(veh.vehtype);
					   
					$("#modal-default").modal('show');
				} else {
					alert(s.msg);
				}
			}
		}); 
   }
   
   function delveh(id)
   {
	   CvMsg.confirm("警告","数据删除后将无法还原！是否删除？",function(){
		   var data = {id:id}
		   $.ajax({
				url : "${request.contextPath}/vehicleinfo/delVeh",
				type : "post",
				data : data,
				success : function(s) {
					if (s.success) {
						location.reload();
					} else {
						alert(s.msg);
					}
				}
			}); 
	   });
   }
   
   function bindveh(vehcode)
   {
	   var id = $("#selveh").val();
	   var data = {id:id,devicecode:vehcode};
	   $.ajax({
			url : "${request.contextPath}/vehicleinfo/bindVeh",
			type : "post",
			data : data,
			success : function(s) {
				if (s.success) {
					
        			$("#modal-default2").modal('hide');
        			location.reload();
				}
			}
		}); 
   }
   
   function showdevdialog(id)
   {
	   /* var data = {id:id}
	   $.ajax({
			url : "${request.contextPath}/vehicleinfo/bindVeh",
			type : "post",
			data : data,
			success : function(s) {
				if (s.success) {
					location.reload();
				} else {
					alert(s.msg);
				}
			}
		});  */
		$("#selveh").val(id);
	   
	   var data = {install:0};
	   $.ajax({
			url : "${request.contextPath}/device/getDevice",
			type : "post",
			data : data,
			success : function(s) {
				if (s.success) {
					
					var devlist = s.other;
					$("#mydev").empty();
        			for(var i=0;i<devlist.length;i++){
        				$("#mydev").append("<tr><td>"+devlist[i].device_id+"</td><td>"+devlist[i].serial_id+"</td><td>"+devlist[i].device_type+"</td><td><button class='btn btn-success btn-small' onclick='bindveh(\""+devlist[i].device_id+"\");'>加</button></td></tr>");
        			}
					
					$("#modal-default2").modal('show');
				} else {
					alert(s.msg);
				}
			}
		});
	   
   }
   
   function saveveh()
   {
	   
	   var vehinfoid = $("#vehinfoid").val();
	   //公司ID
	   var companyid = $("#parentid").val();
	   if (companyid == "")
	   {
		   companyid = null;
	   }
	   else
	   {
		   companyid = parseInt(companyid);
	   }
	   
	   var vehid = $("#vehid").val();
	   var platetype = $("#platetype").val();
	   var vehcolor = $("#vehcolor").val();
	   var status = $("#status").val();
	   var vehtype = $("#vehtype").val();
		   
	   if (vehinfoid == -1)
	   {
		  
		   var data = {
				   vehid:vehid,
				   platetype:platetype,
				   vehcolor:vehcolor,
				   companyid:companyid,
			       status:status,
			       vehtype:vehtype
		   }
		   $.ajax({
				url : "${request.contextPath}/vehicleinfo/saveVeh",
				type : "post",
				data : data,
				success : function(s) {
					if (s.success) {
						location.reload();
					} else {
						alert(s.msg);
					}
				}
			});
	   }
	   else
	   {
		   var data = {
			   id:vehinfoid,
			   vehid:vehid,
			   platetype:platetype,
			   vehcolor:vehcolor,
			   companyid:companyid,
		       status:status,
		       vehtype:vehtype
		   }
		   $.ajax({
				url : "${request.contextPath}/vehicleinfo/updateVeh",
				type : "post",
				data : data,
				success : function(s) {
					if (s.success) {
						location.reload();
					} else {
						alert(s.msg);
					}
				}
			});
	   }
   }
   
   
 </script>